package org.easy.mybatisplus;


import org.easy.mybatisplus.model.ICreateBy;
import org.easy.mybatisplus.model.ICreateTime;
import org.easy.mybatisplus.model.IUpdateBy;
import org.easy.mybatisplus.model.IUpdateTime;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.time.LocalDateTime;

@Aspect
public class DaoAspect {

    @Around(value = "execution(* com.baomidou.mybatisplus.core.mapper.BaseMapper.*(..))")
    public Object updateAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object param = proceedingJoinPoint.getArgs()[0];
        String methodName = proceedingJoinPoint.getSignature().getName();
        handleParam(param, methodName);
        return proceedingJoinPoint.proceed();

    }

    private void handleParam(Object param, String methodName) {
        if (methodName.contains("insert")) {
            insertParam(param);
        }

        if (methodName.contains("update")) {
            updateParam(param);
        }
    }


    /**
     * 插入的时候自动注入闯 创建时间，未删除状态，租户id
     *
     * @param param
     */
    protected void insertParam(Object param) {
        if (param instanceof ICreateTime) {
            ((ICreateTime) param).setCreateTime(LocalDateTime.now());
        }

        if (param instanceof ICreateBy) {
            ((ICreateBy) param).setCreateBy(1L);
        }

    }

    private void updateParam(Object param) {
        if (param instanceof IUpdateTime) {

            ((IUpdateTime) param).setUpdateTime(LocalDateTime.now());
        }

        if (param instanceof IUpdateBy) {
            ((IUpdateBy) param).setUpdateBy(1L);
        }
    }

}
